package com.tulele.vtool.handler;

import com.google.common.collect.Maps;
import com.tulele.vtool.model.PlatformSysInfo;
import com.tulele.vtool.model.UserInfo;
import com.tulele.vtool.model.reqEntity.Get51ActivityCertificateReqBean;
import com.tulele.vtool.model.respEntity.RespData;
import com.tulele.vtool.model.respEntity.ReturnCode;
import com.tulele.vtool.service.IUserInfoService;
import com.tulele.vtool.service.SysGzhService;
import com.tulele.vtool.utils.*;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import com.tulele.vtool.wechat.service.WeixinServiceNew;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

@RestController
public class PlatformActivityHandler {

//    @Autowired
//    private WeixinService weixinService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private SysGzhService sysGzhService;

//    @Autowired
//    private ObjectFactory<WeixinServiceDL> objectFactory;

    @PostMapping(value = "/get51ActivityPublicNumQrCode", produces="application/json;charset=UTF-8")
    public RespData get51ActivityPublicNumQrCode(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive) {

        String qrCodeImgUrl = null;

        Map<String, String> resultMap = Maps.newHashMap();

        qrCodeImgUrl = (String)redisCacheUtil.getCacheObject("paLongTermQrCodeImgUrl");
        if (StringUtils.isNotBlank(qrCodeImgUrl)) {

            resultMap.put("paLongTermQrCodeImgUrl", qrCodeImgUrl);

            RespData respData = new RespData();
            respData.setData(resultMap);
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");
            return respData;

        }

        String sceneStr = "51ai";
        String qrCodeImgOssDir = "platformActivity";
        String platformActivityAccessPrefix = "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/";

        try {

//            WeixinServiceDL weixinService= objectFactory.getObject();
//            weixinService.reSetConfigStorage(springProfilesActive);
            PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
            //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
            WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);

            WxMpQrCodeTicket ticket = weixinService.getQrcodeService().qrCodeCreateLastTicket(sceneStr);
            File qrCodeImgFile = weixinService.getQrcodeService().qrCodePicture(ticket);

            String fileName = UUID.randomUUID().toString() + ".png";

            String formatDate = DateUtil.getFormatDate("yyyy-MM-dd", DateUtil.getCurDate());
            String dirName = qrCodeImgOssDir + "/" + formatDate + "/";

            AliyunOssClientUtil.uploadFileByLocalFile(qrCodeImgFile, dirName + fileName);

            qrCodeImgUrl = platformActivityAccessPrefix + dirName + fileName;

            redisCacheUtil.setCacheObject("paLongTermQrCodeImgUrl", qrCodeImgUrl, 864000);

            resultMap.put("paLongTermQrCodeImgUrl", qrCodeImgUrl);


        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        RespData respData = new RespData();
        respData.setData(resultMap);
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setMsg("成功");
        return respData;

    }

    @PostMapping(value = "/get51ActivityCertificateImg", produces="application/json;charset=UTF-8")
    public RespData get51ActivityCertificate(@RequestHeader("userId") String userId,@RequestHeader("identifying") String springProfilesActive, @RequestBody Get51ActivityCertificateReqBean get51ActivityCertificateReqBean) {

        int concernStatus = Optional.ofNullable(userInfoService.getUserConcernStatus(Integer.parseInt(userId))).orElse(0);

        String sceneStr = "51ai";
        String platformActivityImgOssDir = "platformActivity";
        String platformActivityAccessPrefix = "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/";

        Map<String, Object> resultMap = Maps.newHashMap();

        resultMap.put("concernStatus", concernStatus);

        if (concernStatus == 0) {

            String qrCodeImgUrl = null;

            try {
//                WeixinServiceDL weixinService= objectFactory.getObject();
//                weixinService.reSetConfigStorage(springProfilesActive);
                PlatformSysInfo platformSysInfoConfig= sysGzhService.getPlatformSysInfo(springProfilesActive);
                //WxMpServiceImpl weixinService = WeixinServiceNew.getWeixinService(platformSysInfoConfig.getSysGzh());
                WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(springProfilesActive);

                WxMpQrCodeTicket ticket = weixinService.getQrcodeService().qrCodeCreateLastTicket(sceneStr);
                File qrCodeImgFile = weixinService.getQrcodeService().qrCodePicture(ticket);

                String fileName = UUID.randomUUID().toString() + ".png";

                String formatDate = DateUtil.getFormatDate("yyyy-MM-dd", DateUtil.getCurDate());
                String dirName = platformActivityImgOssDir + "/" + formatDate + "/";

                AliyunOssClientUtil.uploadFileByLocalFile(qrCodeImgFile, dirName + fileName);

                qrCodeImgUrl = platformActivityAccessPrefix + dirName + fileName;

                redisCacheUtil.setCacheObject("paLongTermQrCodeImgUrl", qrCodeImgUrl, 864000);

                resultMap.put("paLongTermQrCodeImgUrl", qrCodeImgUrl);

            } catch (WxErrorException e) {
                e.printStackTrace();
            }

            RespData respData = new RespData();
            respData.setData(resultMap);
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");
            return respData;

        } else {

            try {

                UserInfo userInfo = userInfoService.getUserMainInfo(Integer.parseInt(userId));

                //下载用户头像
                String avatarName = UUID.randomUUID().toString() + ".jpg";
                ToolUtil.downloadAvatarPic(userInfo.getAvatarUrl(), userInfo.getUserId(), avatarName);

                String avatarPath = SysConstant.WX_AVATAR_DOWNLOAD_PATH + userInfo.getUserId() + "/" + avatarName;

                String telNum = userInfo.getTelNum();
                String desc = null;

                if (StringUtils.isNotBlank(telNum)) {
                    desc = "电话: " + userInfo.getTelNum();;
                }

                String imgeName = get51ActivityCertificateReqBean.getImgName();
                File resultImg = SharedActivityImageUtils.generate51ActivitySharedImage(avatarPath, imgeName, userInfo.getNickName(), desc);

                String formatDate = DateUtil.getFormatDate("yyyy-MM-dd", DateUtil.getCurDate());
                String dirName = platformActivityImgOssDir + "/" + userId + "/" + formatDate + "/";
                String fileName = UUID.randomUUID().toString() + ".png";

                AliyunOssClientUtil.uploadFileByLocalFile(resultImg, dirName + fileName);

                String certificateImgUrl = platformActivityAccessPrefix + dirName + fileName;

                resultMap.put("certificateImgUrl", certificateImgUrl);

            } catch (WxErrorException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

            RespData respData = new RespData();
            respData.setData(resultMap);
            respData.setCode(ReturnCode.NORMAL_SUCC);
            respData.setMsg("成功");
            return respData;

        }

    }

    @PostMapping(value = "/getActivityUserInfo", produces="application/json;charset=UTF-8")
    public RespData getUserBusinessCardInfo(@RequestHeader("userId") String userId) {

        Integer userIdInt = Integer.valueOf(userId);

        UserInfo userInfo = userInfoService.getUserMainInfo(userIdInt);

        HashMap<String, Object> userInfoMap = Maps.newHashMapWithExpectedSize(9);
        userInfoMap.put("userId", userInfo.getUserId());
        userInfoMap.put("avatarUrl", userInfo.getAvatarUrl());
        userInfoMap.put("nickName", userInfo.getNickName());
        userInfoMap.put("telNum", userInfo.getTelNum());

        Integer activityAttendCount = Optional.ofNullable((Integer) redisCacheUtil.getCacheObject("activityAttendCount")).orElse(181000);
        userInfoMap.put("activityAttendCount", activityAttendCount);

        userInfoMap.put("smallShareImgUrl", "https://zktuistatic.oss-cn-shenzhen.aliyuncs.com/platformActivity/51background/smallShare.jpg");

        userInfoMap.put("shareMsg", "地球不爆炸，我们不放假，快来领取你的劳模证。\n");

        int count = ToolUtil.randomNum(1, 10);
        redisCacheUtil.setCacheObject("activityAttendCount", activityAttendCount + count, 864000);

        RespData respData = new RespData();
        respData.setCode(ReturnCode.NORMAL_SUCC);
        respData.setData(userInfoMap);
        respData.setMsg("成功");
        return respData;
    }

}
